package com.easy.leetcode;

/**
 * @ClassName MyPow50
 * @Description TODO
 * @Author zheng
 * @Date 2021/12/3 16:43
 * @Version 1.0
 **/
public class MyPow50 {
    /**
     * @return double
     * @Description 暴力，超时（垃圾）
     * @Date 2021/12/3 16:56
     * @Param [x, n]
     **/
    public double myPow1(double x, int n) {
        int tmp = Math.abs(n);
        double res = 1;
        while (tmp > 0) {
            tmp--;
            res *= x;
        }
        return n > 0 ? res : 1 / res;
    }

    public double myPow(double x, int n) {
        return n > 0 ? help(x, n) : 1 / help(x, Math.abs(n));
    }

    public double help(double x, int n) {
        //退出条件
        if (n == 0) {
            return 1.0;
        }
        //每次折半，求得结果
        double y = help(x, n / 2);
        //折半有余数，那么返回 结果平方*x,否 结果的平方
        return n % 2 == 0 ? y * y : y * y * x;
    }

    public static void main(String[] args) {
        MyPow50 myPow50 = new MyPow50();
        System.out.println(myPow50.myPow(1.0, 2147483647));
    }
}
